package com.nut.course.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * https://help.aliyun.com/document_detail/39630.html?spm=a2c4g.11186623.6.680.437614faQsqHj0
 */
@Component
@Slf4j
public class OssUtils {

//    endpoint: oss-cn-beijing.aliyuncs.com
//    accessId: LTAI4GKsDdZVdzA2mhvg2JFL
//    secretKey: nmcJ8taioYHtqDMj36UiNyFsPq0Pyj
//    bucketName: school2021

    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String bucketName;

    //    public static final String endpoint = "oss-cn-beijing.aliyuncs.com";
//    public static final String accessKeyId = "LTAI4GKsDdZVdzA2mhvg2JFL";
//    public static final String accessKeySecret = "nmcJ8taioYHtqDMj36UiNyFsPq0Pyj";
//    public static final String bucketName = "school2021";
    // 设置URL过期时间为10年  3600L* 1000*24*365*10
    public static final long TEN_YEAR = 3600L * 1000 * 24 * 365 * 10;


    public static final String CONTENT_TYPE_JPG = "image/jpg";
    public static final String CONTENT_TYPE_PNG = "image/png";
    public static final String DOMAIN_OLD = "school2021.oss-cn-beijing.aliyuncs.com";
    public static final String DOMAIN_NEW = "jwtimg.bajiutuan.com";


    /**
     * 下载文件
     *
     * @param objectName 文件路径及文件名称 如：banner/20190220/test.txt
     * @param fileName   本地文件名
     */
    public static void downloadFile(String objectName, String fileName) {
        OSS client = null;
        try {
            client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            client.getObject(new GetObjectRequest(bucketName, objectName), new File(fileName));
        } catch (Exception e) {
            log.error("下载文件异常：{}", e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
    }

    /**
     * 批量删除oss资源
     *
     * @param objectNames 文件路径+文件名的集合  如：['banner/20190220/test.txt', 'banner/20190220/test1.txt']
     * @return
     */
    public static void batchDeleteFile(List<String> objectNames) {
        // 创建OSSClient实例。
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        DeleteObjectsResult deleteObjectsResult = client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNames));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        if (deletedObjects.size() > 0) {
            log.warn("删除失败的文件：{}", deletedObjects.toString());
        }
        // 关闭OSSClient。
        client.shutdown();
    }


    public static String uploadFile(String fileName, String value) {
        if (value == null) {
            return null;
        }
        InputStream is = new ByteArrayInputStream(value.getBytes());
        return uploadFile(bucketName, fileName, is, null);
    }

    public static String uploadFile(String fileName, InputStream is) {
        return uploadFile(bucketName, fileName, is, null);
    }

    public static String uploadFile(String fileName, InputStream is, String contentType) {
        return uploadFile(bucketName, fileName, is, contentType);
    }

    public static String uploadFile(String bucketName, String fileName, byte[] data) {
        ByteArrayInputStream is = new ByteArrayInputStream(data);
        return uploadFile(bucketName, fileName, is, null);
    }

    /**
     * 上传文件
     *
     * @param bucketName
     * @param objectName  文件名   /jwt/2021/02/图片
     * @param inputStream 文件流
     * @param contentType image/jpg  image/png
     * @return 访问地址
     */
    public static String uploadFile(String bucketName, String objectName, InputStream inputStream, String contentType) {
        OSS client = null;
        try {
            client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            if (contentType != null) {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(contentType);
                client.putObject(bucketName, objectName, inputStream, metadata);
            } else {
                client.putObject(bucketName, objectName, inputStream);
            }

            return getUrl(bucketName, objectName, client);
        } catch (Exception e) {
            log.error("upload_img_error", e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return "";
    }

    /**
     * 生成文件访问的路径
     *
     * @param objectName 文件路径及文件名称 如：banner/20190220/test.txt
     * @param client
     * @return
     */
    private static String getUrl(String bucketName, String objectName, OSS client) {
        Date expiration = new Date(System.currentTimeMillis() + TEN_YEAR);
        // 生成URL
        URL url = client.generatePresignedUrl(bucketName, objectName, expiration);
        if (url != null) {
            // 替换域名
            return url.toString().replace(DOMAIN_OLD, DOMAIN_NEW);
        }
        return null;
//        return url == null ? null : url.toString();
    }

    public static String generateFileName(String ext) {
        LocalDateTime now = LocalDateTime.now();
        StringBuilder sb = new StringBuilder();
        sb.append("jwt/");
        sb.append(now.getYear());
        sb.append("/");
        sb.append(now.getMonthValue() < 10 ? "0" + now.getMonthValue() : now.getMonthValue());
        sb.append("/");
        sb.append(System.currentTimeMillis());
        if (ext != null) {
            sb.append("." + ext);
        }
        return sb.toString();
    }

    @Value("${oss.endpoint}")
    public void setendpoint(String endpoint) {
        OssUtils.endpoint = endpoint;
    }

    @Value("${oss.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        OssUtils.accessKeyId = accessKeyId;
    }

    @Value("${oss.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        OssUtils.accessKeySecret = accessKeySecret;
    }

    @Value("${oss.bucketName}")
    public void setBucketName(String bucketName) {
        OssUtils.bucketName = bucketName;
    }

    public static void main(String args[]) throws IOException {

//        uploadFile("ddd", "value");

//        String fileName = "D:\\luban\\ee.jpg";
        String fileName = "E:\\luban\\ee.png";
        File file = new File(fileName);
//        String s1 = uploadFile(System.currentTimeMillis() + ".png", new FileInputStream(file));
//        System.out.println(s1);

//        byte[] value = downloadFile("ddd");
//        String s = new String(value);
//        System.out.println(s);


//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        String name = System.currentTimeMillis() + "";
//        ObjectMetadata metadata = new ObjectMetadata();
//        metadata.setContentType("image/jpg");
//
//        PutObjectResult putObjectResult = ossClient.putObject(bucketName, name, new FileInputStream(file), metadata);
//        System.out.println(putObjectResult);
//        Date expiration = new Date(System.currentTimeMillis() + TEN_YEAR);
//        // 生成URL
//        URL url = ossClient.generatePresignedUrl(bucketName, name, expiration);
//
//        System.out.println(url.toString());
//        ossClient.shutdown();


        String name = generateFileName("jpg");

        String url = uploadFile(bucketName, name, new FileInputStream(file), CONTENT_TYPE_JPG);
        System.out.println(url);

//        http://school2021.oss-cn-beijing.aliyuncs.com/jwt/2021/02/1614440621877?Expires=1929800636&OSSAccessKeyId=LTAI4GKsDdZVdzA2mhvg2JFL&Signature=dbnpShVLjgqlJC%2BtRMfIrpfgS1Y%3D
//        http://jwtimg.bajiutuan.com/jwt/2021/02/1614440621877?Expires=1929800636&OSSAccessKeyId=LTAI4GKsDdZVdzA2mhvg2JFL&Signature=dbnpShVLjgqlJC%2BtRMfIrpfgS1Y%3D
//        http://jwtimg.bajiutuan.com/1614437310880?Expires=1929797319&OSSAccessKeyId=LTAI4GKsDdZVdzA2mhvg2JFL&Signature=rGX5X2xU8%2BulPaVfnOX1rhte9z0%3D
//        uploadFile(bucketName,"JWt")


//        System.out.println(LocalDateTime.now().getYear());
//        System.out.println(LocalDateTime.now().getMonthValue());
//        System.out.println(generateFileName());

    }
}
